<script setup lang="tsx">
defineOptions({
  name: "ELECTRICTITY_OPERATION_TASKVIEW"
});
import { ref, onMounted, computed, reactive, unref } from "vue";
import { useRouter, useRoute } from "vue-router";
import fullScreen from "@/assets/svg/common/fullScreen.svg?component";

import { useRouterStoreHook } from "@/store/modules/router";
import modelBox from "@/views/common/components/modelBox/index.vue";
import TaskStatus from "./components/TaskStatus.vue";
import TaskCount from "./components/TaskCount.vue";
import { queryTaskCount, queryTaskList } from "@/api/modules/operation";
import { queryChildByTypeCodeAndItemValue } from "@/api/common";
import { getEmployeeIdAndNameByClassCode } from "@/utils/pengxi";
import { getToken } from "@/utils/auth";
import dayjs from "dayjs";
import { PxMessage } from "px-ui";

const router = useRouter();
const route = useRoute();
const routerStore = useRouterStoreHook();
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  clazzCode: routerStore.getSubject === "ALL" ? "" : routerStore.getSubject,
  timeRange: [dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss"), dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss")],
  taskTitle: "", //任务名称
  taskModuleTypeCode: [], //任务类型
  taskModuleSingle: "", // 查询条件里的单个code
  taskOwner: [], //执行人
  taskOwnerSingle: "", // 查询条件里的单个code
  taskStatus: [],
  taskStatusSingle: "" // 查询条件里的单个code
});
const categroyList = ref([]);
const total = ref(0);
const tableData = ref([]);
const countData = ref({});
const userList = ref([]);
const getUserList = async () => {
  userList.value = await getEmployeeIdAndNameByClassCode([queryParams.clazzCode], "username");
};
const handleParams = () => {
  if (queryParams.taskModuleSingle) {
    queryParams.taskModuleTypeCode = [queryParams.taskModuleSingle];
  } else {
    queryParams.taskModuleTypeCode = [];
  }
  if (queryParams.taskStatusSingle) {
    queryParams.taskStatus = [queryParams.taskStatusSingle];
  } else {
    queryParams.taskStatus = [];
  }
  if (queryParams.taskOwnerSingle) {
    queryParams.taskOwner = [queryParams.taskOwnerSingle];
  } else {
    queryParams.taskOwner = [];
  }
  if (queryParams.taskModuleSingle) {
    categroyList.value.forEach(v => {
      if (queryParams.taskModuleSingle == v.code) {
        if (queryParams.taskStatusSingle && queryParams.taskStatusSingle == "UNDO") {
          v.activeStatus = "UNDO";
        } else if (queryParams.taskStatusSingle && queryParams.taskStatusSingle == "DONE") {
          v.activeStatus = "";
        } else {
          v.activeStatus = "ALL";
        }
      } else {
        v.undoTasks = undefined;
        v.doneTasks = undefined;
        v.totalTasks = undefined;
      }
    });
  }
};
const getTaskCount = async () => {
  try {
    handleParams();
    let res = await queryTaskCount({ ...queryParams, startTime: queryParams.timeRange[0], endTime: queryParams.timeRange[1] });
    let totalNum = 0;
    let undoNum = 0;
    let doneNum = 0;
    if (res && res.length) {
      categroyList.value.forEach(v => {
        let target = res.filter(r => r.taskModuleName == v.code);
        if (target && target.length) {
          v.undoTasks = target[0].undoTasks;
          v.doneTasks = target[0].doneTasks;
          v.totalTasks = target[0].totalTasks;
          totalNum += v.totalTasks;
          undoNum += v.undoTasks;
          doneNum += v.doneTasks;
        } else {
          v.undoTasks = undefined;
          v.doneTasks = undefined;
          v.totalTasks = undefined;
        }
      });
    } else {
      categroyList.value.map(v => {
        v.undoTasks = undefined;
        v.doneTasks = undefined;
        v.totalTasks = undefined;
      });
    }
    countData.value = {
      totalNum,
      undoNum,
      doneNum
    };
  } catch (error) {}
};
const getTaskList = async () => {
  try {
    handleParams();
    let res = await queryTaskList({ ...queryParams, startTime: queryParams.timeRange[0], endTime: queryParams.timeRange[1] });
    tableData.value = res.data;
    total.value = res.total;
  } catch (error) {}
};
const statusList = ref([
  {
    name: "未完成",
    value: "UNDO"
  },
  {
    name: "已完成",
    value: "DONE"
  }
]);
const getCategroyList = async () => {
  const data: any = await queryChildByTypeCodeAndItemValue({
    value: "MODULE",
    typeCode: "OPERATION_TASKBOARD"
  });
  if (data && data.length) {
    data.forEach(v => {
      categroyList.value.push({
        name: v.itemName,
        code: v.itemValue,
        activeStatus: ""
      });
    });
  } else {
    categroyList.value = [];
  }
  if (route.query.taskTypeCode) {
    queryParams.taskModuleSingle = route.query.taskTypeCode;
  }
  if (route.query.taskStatusCode) {
    queryParams.taskStatusSingle = route.query.taskStatusCode;
  }
  queryTable(false);
};
const toFullScreen = () => {
  const path = "/fullScreen/electricity/operation/taskView";
  const { subject: className } = routerStore;
  const query = { className };
  const params = { path, query };
  const { href } = router.resolve(params);
  window.open(href, "_blank");
};
const paramsChange = params => {
  let type = params.type;
  let activeStatus = params.type;
  let code = categroyList.value[params.index]?.code || "";
  if (params.type == "ALL") {
    type = "";
  }
  if (
    (queryParams.taskStatusSingle && type != queryParams.taskStatusSingle) ||
    (code && queryParams.taskModuleSingle && code != queryParams.taskModuleSingle)
  ) {
    PxMessage.error("与筛选条件冲突，请重置后查询");
    return;
  }
  if (categroyList.value[params.index]?.activeStatus && categroyList.value[params.index]?.activeStatus == activeStatus) {
    // 切换选中与取消
    type = "";
    code = "";
    activeStatus = "";
  }
  categroyList.value.map(v => (v.activeStatus = ""));
  if (categroyList.value[params.index]) {
    categroyList.value[params.index].activeStatus = activeStatus;
  }
  if (code) {
    queryParams.taskModuleSingle = code;
  }

  queryParams.taskStatusSingle = type;
  queryTable(true);
};
const queryTable = type => {
  if (queryParams.timeRange) {
    if (!type) {
      categroyList.value.map(v => (v.activeStatus = ""));
    }
    getTaskCount();
    getTaskList();
  } else {
    PxMessage.error("请选择时间后查询");
  }
};
const resetTable = () => {
  queryParams.pageNum = 1;
  queryParams.pageSize = 20;
  queryParams.clazzCode = routerStore.getSubject === "ALL" ? "" : routerStore.getSubject;
  queryParams.timeRange = [dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss"), dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss")];
  queryParams.taskTitle = ""; //任务名称
  queryParams.taskModuleTypeCode = []; //任务类型
  queryParams.taskModuleSingle = ""; // 查询条件里的单个code
  queryParams.taskOwner = []; //执行人
  queryParams.taskOwnerSingle = ""; // 查询条件里的单个code
  queryParams.taskStatus = [];
  queryParams.taskStatusSingle = "";
  queryTable(false);
};

const accessToken = getToken().accessToken || "";
const goTaskDetail = row => {
  const httpReg = /^http(s?):\/\//;
  if (row.taskModuleName == "PMS") {
    if (row.taskResourceUrl) {
      let url = `${row.taskResourceUrl}&ssoToken=${accessToken}&facCode=${localStorage.getItem("facCode")}`;
      window.open(url);
    }
  } else if (row.taskModuleName == "OCAP") {
    let url = `${window.location.protocol}//${window.location.host}/all/safeManage/abnormal/apply?pageType=detail&handlerId=${row.taskResourceId}`;
    window.open(url);
  } else if (row.taskResourceUrl) {
    if (httpReg.test(row.taskResourceUrl)) {
      window.open(row.taskResourceUrl);
    } else {
      let url = `${window.location.protocol}//${window.location.host}${row.taskResourceUrl}`;
      window.open(url);
      //  router.push({ path: row.taskResourceUrl });
    }
  } else {
    console.log("未配置url");
    PxMessage.error("未配置url");
  }
  // if (row.type == "保养任务") {
  //   router.push({
  //     path: "/all/equip/epm/task/list",
  //     query: {
  //       fullpath: `/pmJob/list?jobId=${row.id}&jobStatus=${row.params.status || ""}&pmType=${row.params.pmType}&status=${row.statusDesc || ""}&ssoToken=${accessToken}&isHiddenMenu=true`
  //     }
  //   });
  // }
  // if (row.type == "维修任务") {
  //   router.push(`/all/equip/maintain/task?id=${row.id}&status=${row.params.workOrderStatus || ""}&type=view&tabName=0`);
  // }
  // if (row.type == "巡检任务") {
  //   router.push({ path: "/all/equip/inspect/task", query: { taskCode: row.id } });
  // }
};
const getNameByCode = (list, key, value, name) => {
  let nameList = [];
  if (list.length) {
    let dataList = unref(list);
    if (dataList.length) {
      let userIds = value.split(",");
      if (value) {
        userIds.forEach(item => {
          let obj = dataList.filter(v => v[key] == item);
          if (obj.length) {
            nameList.push(obj[0][name]);
          }
        });
      }
    }
  }
  return nameList.join(",");
};
onMounted(() => {
  getCategroyList();
  getUserList();
});
</script>

<template>
  <div class="ele-task-overview">
    <div class="gas-overview-item all search">
      <px-form class="custom-form-ui equip-form" :model="queryParams" inline label-width="120px">
        <px-row :gutter="16">
          <px-col :span="4">
            <px-form-item label="任务类型" prop="type">
              <px-select v-model="queryParams.taskModuleSingle" clearable filterable>
                <px-option v-for="item in categroyList" :key="item.code" :label="item.name" :value="item.code" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="4">
            <px-form-item label="任务名称" prop="taskTitle">
              <px-input v-model="queryParams.taskTitle" clearable />
            </px-form-item>
          </px-col>
          <px-col :span="5">
            <px-form-item label="时间" prop="timeRange">
              <px-date-picker
                v-model="queryParams.timeRange"
                clearable
                type="datetimerange"
                range-separator="至"
                start-placeholder="请选择开始时间"
                end-placeholder="请选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="[new Date(2000, 0, 1, 0, 0, 0), new Date(2000, 0, 1, 23, 59, 59)]"
              />
            </px-form-item>
          </px-col>
          <px-col :span="4">
            <px-form-item label="任务状态" prop="taskStatusSingle">
              <px-select v-model="queryParams.taskStatusSingle" clearable filterable>
                <px-option v-for="item in statusList" :key="item.value" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="4">
            <px-form-item label="执行人" prop="taskOwnerSingle">
              <px-select v-model="queryParams.taskOwnerSingle" clearable filterable>
                <px-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
              <!-- <px-select-v2
                v-model="queryParams.taskOwnerList"
                style="width: 100%"
                multiple
                collapse-tags
                collapse-tags-tooltip
                clearable
                filterable
                :options="userList"
                placeholder="请选择"
              /> -->
            </px-form-item>
          </px-col>
          <px-col :span="3">
            <px-button type="primary" @click="queryTable(false)">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
    </div>
    <div class="gas-overview-item all total">
      <modelBox title="任务统计">
        <TaskCount :categroyList="categroyList" :countData="countData" :taskStatus="queryParams.taskStatusSingle" @paramsChange="paramsChange" />
      </modelBox>
    </div>
    <div class="gas-overview-item all list">
      <modelBox title="任务清单">
        <px-table :data="tableData" show-overflow-tooltip class="light-table" stripe :height="'calc(100vh - 608px)'">
          <template #empty>
            <px-empty />
          </template>
          <px-table-column label="序号" width="60" align="center" fixed="left">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>
          <px-table-column prop="taskId" label="任务编号" min-width="130">
            <template #default="scope">
              <px-link type="primary" @click="goTaskDetail(scope.row)">{{ scope.row.taskId }}</px-link>
            </template>
          </px-table-column>
          <px-table-column prop="taskModuleName" label="任务类型" min-width="120">
            <template #default="scope">
              {{ getNameByCode(categroyList, "code", scope.row.taskModuleName, "name") || "其他任务" }}
            </template>
          </px-table-column>
          <px-table-column prop="taskTitle" label="任务名称" min-width="180" />
          <px-table-column prop="taskPlanTime" label="任务开始时间" min-width="140">
            <template #default="scope">
              {{ scope.row.taskPlanTime || "-" }}
            </template>
          </px-table-column>
          <px-table-column prop="taskFinishTime" label="任务结束时间" min-width="140">
            <template #default="scope">
              {{ scope.row.taskFinishTime || "-" }}
            </template>
          </px-table-column>
          <px-table-column prop="taskHandleTime" label="实际完成时间" min-width="140">
            <template #default="scope">
              {{ scope.row.taskHandleTime || "-" }}
            </template>
          </px-table-column>
          <px-table-column prop="taskStatus" label="任务状态" min-width="100">
            <template #default="scope">
              <TaskStatus :status="scope.row.taskStatus" />
            </template>
          </px-table-column>
          <px-table-column prop="taskOwner" label="执行人" min-width="150" />
          <px-table-column prop="taskOwnerPhone" label="联系电话" width="120" />
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @pagination="getTaskList"
        />
      </modelBox>
    </div>

    <div class="full-screen">
      <fullScreen class="icon" @click="toFullScreen" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.ele-task-overview {
  position: relative;
  box-sizing: border-box;
  display: grid;
  grid-template-columns: repeat(24, minmax(16px, 1fr));
  grid-auto-rows: 66px 232px auto;
  // grid-auto-rows: 233px 263px 263px;
  // grid-auto-rows: 4fr 5fr 5fr;
  grid-auto-flow: column dense;
  grid-gap: 16px;
  width: 100%;

  .full-screen {
    position: absolute;
    top: -10px;
    right: -16px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    cursor: pointer;
    background-color: var(--px-color-primary-light-9);
    border-radius: 4px;
    box-shadow: 0 0 4px 0 var(--px-color-primary-light-3);

    .icon {
      width: 70%;
      height: 70%;
      color: var(--px-color-primary);
    }

    &:hover {
      background-color: var(--px-color-primary-light-7);
      box-shadow: none;
    }
  }

  .gas-overview-item {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    border-radius: 4px;
  }

  .all {
    grid-column: 1 / 25;

    &.search {
      justify-content: flex-start;
      min-height: 32px;
      padding: 16px;

      .equip-form {
        :deep(.px-form-item) {
          width: 100%;
          margin-bottom: 8px;

          .px-input {
            width: 100%;
          }

          .px-select {
            width: 100%;
          }

          .px-select-v2 {
            width: 100%;

            .px-select-v2__wrapper {
              cursor: pointer;
            }
          }
        }

        :deep(.px-button + .px-button) {
          margin-left: 8px;
        }
      }
    }

    &.total {
      height: 232px;
    }

    &.list {
      height: 100%;
      min-height: 452px; // 530px
    }
  }

  .one {
    grid-column: 1 / 7;
  }

  .two {
    grid-column: 7 / 21;
  }

  .three {
    grid-column: 21 / 25;
  }

  .four {
    grid-column: 1 / 19;
  }

  .five {
    grid-column: 19 / 25;
  }

  .six {
    grid-column: 1 / 19;
  }

  .seven {
    grid-column: 19 / 25;
  }
}

.light-table {
  --px-table-border-color: transparent;
  --px-table-border: none;
  --px-table-text-color: #4f4f4f;
  --px-table-header-text-color: #4f4f4f;
  --px-table-row-hover-bg-color: transparent;
  --px-table-current-row-bg-color: transparent;
  --px-table-header-bg-color: transparent;
  --px-table-bg-color: transparent;
  --px-table-tr-bg-color: transparent;
  --px-table-expanded-cell-bg-color: transparent;
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table__cell) {
  background-color: #fff !important;
}

:deep(.px-table .px-table__header-wrapper th, .px-table .px-table__fixed-header-wrapper th) {
  font-size: 14px !important;
}

:deep(.px-table--striped) {
  .px-table__body tr.px-table__row--striped td.px-table__cell {
    background-color: var(--px-color-primary-light-9);
  }
}

:deep(.model-title-com) {
  background-repeat: no-repeat;
  background-size: 276px 32px;
}

:deep(.custom-form-ui .px-form-item) {
  margin-bottom: 0 !important;
}

:deep(.echarts-chart) {
  padding: 0;
}
</style>
